import PageFilterComponent from '@/components/PageFilter/index.vue';
import { CertApi, CustomerApi } from '@/api';
import { FileUtils } from '@/utils';
import AApprovalStatusTag from '@/components/AApprovalStatusTag/index.vue';

export default {
  name: 'CustomerList',
  components: { AApprovalStatusTag, PageFilterComponent },
  data() {
    return {
      tableData: {
        page: 1,
        pageSize: 20,
        total: 0,
        list: [],
      },
      filterForm: {
        client_name: null,
        parentId: null,
      },
      tableDataLoading: false,
      customerCategories: [],
    };
  },
  async created() {
    await this.fetchCustomerCategories();
  },
  watch: {
    'filterForm.parentId': function () {
      this.fetchTableData();
    },
  },
  methods: {
    async fetchTableData() {
      if (!this.filterForm.parentId || this.filterForm.parentId === '0') {
        return;
      }
      try {
        this.tableDataLoading = true;
        const response = await CustomerApi.page2({
          page: this.tableData.page,
          pageSize: this.tableData.pageSize,
          ...this.filterForm,
        });
        this.tableData = response.result;
      } catch (e) {
      } finally {
        this.tableDataLoading = false;
      }
    },
    async fetchCustomerCategories() {
      try {
        const response = await CertApi.getDataType();
        this.customerCategories = response.result.list;
        this.filterForm.parentId = response.result.list[0].type_id + '';
      } catch (e) {
        this.$message.error('查询证书类型列表异常:' + e.msg)
      }
    },
    toCustomerDetail(type, id) {
      const baseUrl = '/customer/detail';
      switch (type) {
        case 'ADD':
          this.$router.push({ path: baseUrl });
          break;
        case 'EDIT':
          this.$router.push({ path: baseUrl, query: { id } });
          break;
        case 'VIEW':
          this.$router.push({ path: baseUrl, query: { id, preivew: 1 } });
          break;
        default:
          break;
      }
    },
    onPageChanged(page) {
      this.tableData.page = page;
      this.fetchTableData();
    },
    onPageSizeChanged(pageSize) {
      this.tableData.pageSize = pageSize;
      this.fetchTableData();
    },
    async onDownloadAllAttachment(client_id) {
      const loading = this.$loading({
        lock: true,
        text: '文件打包中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      try {
        const zipResponse = await CustomerApi.getZip(client_id);
        const path = zipResponse.result.path;
        await FileUtils.download(path);
      } catch (e) {
        this.$message.error('接口异常：' + JSON.stringify(e));
      } finally {
        loading.close();
      }
    },
  },
};
